<template>
  <div>
    <Heads title="登录/注册" :types="$route.params.type" :key="$route.params.type+'rl'"></Heads>

    <van-tabs
      v-model="activeName"
      type="card"
      sticky
      animated
      :swipeable="true"
      color="yellowgreen"
    >
      <van-tab title="注册" name="register" :to="{ name: 'User-type', params: { type: 'register' } }">
        <van-cell-group>
          <van-field
            v-model="register.username"
            label="用户名"
            placeholder="请输入用户名"
            required
            clearable
            right-icon="question-o"
            @click-right-icon="Toast('请输入由数字字母_$组成的长度6到10位不能以数字开头')"
            @input="inspect('username')"
            :error-message="inspectList.username.err"
          />
          <van-field
            v-model="register.phone"
            label="手机号"
            type="tel"
            placeholder="请输入手机号"
            right-icon="question-o"
            @click-right-icon="Toast('请输入手机号')"
            @input="inspect('phone')"
            :error-message="inspectList.phone.err"
          />
          <van-field
            v-model="register.password"
            type="password"
            label="密码"
            placeholder="请输入密码"
            required
            right-icon="question-o"
            @click-right-icon="Toast('请输入长度6到12位的数字和字母组成')"
            @input="inspect('password')"
            :error-message="inspectList.password.err"
          />
          <van-field
            v-model="register.dbpwd"
            type="password"
            label="确认密码"
            placeholder="请输入密码"
            required
            right-icon="question-o"
            @click-right-icon="Toast('两次密码必须输入一致')"
            @keyup.enter.native="todoregister"
            @input="inspect('dbpwd')"
            :error-message="inspectList.dbpwd.err"
          />
          <van-button @click="todoregister" type="primary" size="large">注册</van-button>
        </van-cell-group>
      </van-tab>

      <van-tab title="登录" name="login" :to="{ name: 'User-type', params: { type: 'login' } }">
        <van-cell-group>
          <van-field
            v-model="login.phone"
            label="手机"
            type="tel"
            maxlength="11"
            placeholder="请输入手机号"
          />
          <van-field
            v-model="login.password"
            type="password"
            label="密码"
            placeholder="请输入密码"
            @keyup.enter.native="todologin"
          />
          <van-button type="info" size="large" @click="todologin">登录</van-button>
        </van-cell-group>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { post } from "@/utils/axios";
import { mapMutations, mapActions } from "vuex";
import Vue from "vue";
import { Button, NavBar, Icon, Tabs, Tab, CellGroup, Field, Toast } from "vant";
Vue.use(Button)
  .use(NavBar)
  .use(Icon)
  .use(Tabs)
  .use(Tab)
  .use(CellGroup)
  .use(Field)
  .use(Toast);

export default {
  data() {
    return {
      logintab: false,
      register: {},
      login: {},
      inspectList: {
        username: {
          reg: /^[a-zA-Z_$][a-zA-Z0-9_$]{5,9}$/,
          err: ""
        },
        password: {
          reg: /^[a-zA-Z0-9][a-zA-Z0-9]{5,11}$/,
          err: ""
        },
        dbpwd: {
          reg: /^[a-zA-Z0-9][a-zA-Z0-9]{5,11}$/,
          err: ""
        },
        phone: {
          reg: new RegExp(/^1[356789]\d{9}$/),
          err: ""
        }
      }
    };
  },
  computed: {
    // van-tabs
    activeName: {
      get: function() {
        if (this.logintab) {
          return "login";
        } else {
          return this.$route.params.type === "login" ? "login" : "register";
        }
      },
      set: function(newVal, oldVal) {
        // 计算属性的值主动修改
      }
    }
  },
  methods: {
    ...mapMutations("footerModule", ["FOOTERSHOW"]),
    ...mapMutations("userModule", ["CHANGETOKEN", "CHANGEUSERINFO"]),
    ...mapActions("cartModule", ["getCartListAction"]),
    ...mapActions("addressModule", ["getAddressAction"]),
    todoregister() {
      const isErr = () => {
        if (
          this.inspectList.username.err === "" &&
          this.inspectList.phone.err === "" &&
          this.inspectList.password.err === "" &&
          this.inspectList.dbpwd.err === ""
        ) {
          return true;
        } else {
          return false;
        }
      };
      if (isErr()) {
        post({
          url: "/hybrid/users/reg",
          data: { ...this.register }
        }).then(
          res => {
            Toast({
              message: res.msg,
              closeOnClick: true,
              forbidClick: true,
              duration: 500
            });
            if (res.code === 200) {
              this.login.phone = res.result.phone;
              this.logintab = true;
            }
            this.register = {};
          },
          err => {
            console.log(err);
          }
        );
      }
    },
    todologin() {
      if (this.login.phone && this.login.password) {
        post({
          url: "/hybrid/users/login",
          data: { ...this.login }
        }).then(res => {
          if (res.status >= 0) {
            this.CHANGETOKEN(res.result.token);
            this.CHANGEUSERINFO(res.result.userinfo);
            this.getCartListAction();
            this.getAddressAction();
            // TODO: 跳转
            this.$route.params.redirect
              ? this.$router.push(this.$route.params.redirect)
              : this.$router.push({
                  name: "Home"
                });
          } else {
            Toast({
              message: res.msg,
              closeOnClick: true,
              forbidClick: true,
              duration: 500
            });
          }
        });
      } else {
        Toast({
          message: "格式不正确",
          closeOnClick: true,
          forbidClick: true,
          duration: 500
        });
      }
    },
    inspect(type) {
      const isTelCode = str => {
        const reg = this.inspectList[str].reg;
        if (!reg.test(this.register[str])) {
          this.inspectList[str].err = "格式不正确";
        } else {
          this.inspectList[str].err = "";
        }
      };
      switch (type) {
        case "username":
          isTelCode(type);
          break;
        case "phone":
          isTelCode(type);
          break;
        case "password":
          isTelCode(type);
          break;
        case "dbpwd":
          if (this.register.password === this.register.dbpwd) {
            this.inspectList.dbpwd.err = "";
          } else {
            this.inspectList.dbpwd.err = "两次密码不一致";
          }
          break;
      }
    }
  },
  mounted() {
    this.FOOTERSHOW(false);
  },
  destroyed() {
    this.FOOTERSHOW(true);
    this.logintab = false;
  }
};
</script>

<style lang='scss' scoped></style>
